Page({
    data: {
      username: '',
      password: '',
    },
  
    onUsernameInput(e) {
      this.setData({ username: e.detail.value });
    },
  
    onPasswordInput(e) {
      this.setData({ password: e.detail.value });
    },
  
    handleLogin() {
        const { username, password } = this.data;
      
        const app = getApp();
        const db = app.globalData.db;
      
        // 查询用户信息
        db.collection('users')
          .where({
            username,
            password,
          })
          .get()
          .then(res => {
            if (res.data.length > 0) {
              const user = res.data[0];
      
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1500,
              });
      
              setTimeout(() => {
                wx.setStorageSync('currentUser', user); // 存储当前用户信息
      
                if (user.role === 'admin') {
                  wx.navigateTo({
                    url: '/pages/admin-nav/admin-nav', // 跳转到管理员导航页面
                  });
                } else {
                  wx.navigateTo({
                    url: '/pages/user-nav/user-nav', // 跳转到普通用户导航页面
                  });
                }
              }, 1500);
            } else {
              wx.showToast({
                title: '用户名或密码错误',
                icon: 'none',
                duration: 1500,
              });
            }
          })
          .catch(err => {
            wx.showToast({
              title: '登录失败，请稍后重试',
              icon: 'none',
              duration: 1500,
            });
            console.error(err);
          });
      },
  });